package com.zhiyi.xppay.ui;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhiyi.item.LoginBean;
import com.zhiyi.item.PayInfo;
import com.zhiyi.item.QrCode;
import com.zhiyi.xppay.R;
import com.zhiyi.xppay.consts.AppConst;
import com.zhiyi.xppay.consts.AppConstsNxys;
import com.zhiyi.xppay.hook.AlarmReceiver;
import com.zhiyi.xppay.hook.CustomApplcation;
import com.zhiyi.xppay.hook.DaemonService;
import com.zhiyi.xppay.hook.MBankService;
import com.zhiyi.xppay.hook.RestartCPayService;
import com.zhiyi.xppay.hook.TradeQueryService;
import com.zhiyi.xppay.utils.AbSharedUtil;
import com.zhiyi.xppay.utils.AlipayInfo;
import com.zhiyi.xppay.utils.DBManager;
import com.zhiyi.xppay.utils.JSONParser;
import com.zhiyi.xppay.utils.L;
import com.zhiyi.xppay.utils.MD5;
import com.zhiyi.xppay.utils.OrderBean;
import com.zhiyi.xppay.utils.PayHelperUtils;
import com.zhiyi.xppay.utils.QrCodeBean;
import com.zhiyi.xppay.utils.ToolsNxys;
import com.zhiyi.xppay.ws.WsManager;
import com.zhiyi.xppay.ws.WsStatusListener;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import de.robv.android.xposed.XposedBridge;
import okhttp3.OkHttpClient;
import okio.ByteString;

//这个文件是版本忽略的.请.自己创建
//复制目录下的ConnectInfo2 重新命名下

public class MainActivity extends Activity {

    public static TextView console;
    private static ScrollView scrollView;
    private BillReceived billReceived;
    private AlarmReceiver alarmReceiver;
    private ScreenBroadcastReceiver screenReceiver;
    private String currentWechat = "";
    private String currentAlipay = "";
    private String currentQQ = "";
    private String currentCPay = "";
    private String currentLKL = "";
    private String currentNXYS = "";
    private String currentNXYS_WX = "";
    public static final String TYPE_ALIPAY = AppConst.TYPE_ALIPAY;
    public static final String TYPE_WX = AppConst.TYPE_WXPAY;
    public static final String TYPE_QQ = AppConst.TYPE_QQPAY;

    private WebView webView;

    private static MainActivity slef;

    private WsManager wsManager;
    private EditText etNo;
    private TextView txt_id, txt_key;
    public static final String autocheckOrder = "com.android.unionpay.autochexk";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        slef = this;
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (true) {
            setContentView(R.layout.activity_main_debug);
            console = (TextView) findViewById(R.id.console);
            scrollView = (ScrollView) findViewById(R.id.scrollview);
        } else {
            setContentView(R.layout.activity_main);
            initView();
        }

        txt_id =  findViewById(R.id.txt_id);
        txt_key = findViewById(R.id.txt_key);
        String userId = AbSharedUtil.getString(slef, "userId");
        String applyId = AbSharedUtil.getString(slef, "applyId");
        if(!TextUtils.isEmpty(userId)){
            txt_id.setText("商户ID：" + userId);
        }
        if(!TextUtils.isEmpty(applyId)){
            txt_key.setText("应用ID：" + applyId);
        }



/*        etNo = findViewById(R.id.et_no);
        String agencyNo = AbSharedUtil.getString(slef, "agencyNo");
        if (!TextUtils.isEmpty(agencyNo)) {
            etNo.setText(agencyNo);
        }*/

        //注册广播
        billReceived = new BillReceived();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConst.BILLRECEIVED_ACTION);
        intentFilter.addAction(AppConst.MSGRECEIVED_ACTION);
        intentFilter.addAction(AppConst.QRCODERECEIVED_ACTION);
        intentFilter.addAction(AppConst.TRADENORECEIVED_ACTION);
        intentFilter.addAction(AppConst.LOGINIDRECEIVED_ACTION);
        intentFilter.addAction(AppConst.NOT_LOGIN_ACTION);
        // 云闪付
        intentFilter.addAction(AppConst.CP_GETPAYERLIST);
        intentFilter.addAction(AppConst.CP_START);
        // 拉卡拉
        intentFilter.addAction(AppConst.LKL_START);
        // 网商银行
        intentFilter.addAction(AppConst.MBANK_SERVICE);
        registerReceiver(billReceived, intentFilter);

        alarmReceiver = new AlarmReceiver();
        IntentFilter alarmIntentFilter = new IntentFilter();
        alarmIntentFilter.addAction(AppConst.NOTIFY_ACTION);
        registerReceiver(alarmReceiver, alarmIntentFilter);
        startService(new Intent(this, DaemonService.class));
        String[] proms = new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS};
        /*if (!checkPermission(this, proms)) {
            ActivityCompat.requestPermissions(MainActivity.this, proms, 2);
        } else {
            startService(new Intent(this, SmsService.class));
        }*/

        // 注册屏幕状态Receiver
        screenReceiver = new ScreenBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        registerReceiver(screenReceiver, filter);


        findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                connectToWsServer();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            Intent intent = new Intent(autocheckOrder);
                            sendBroadcast(intent);
                            SystemClock.sleep(1000 * 2);
                        }
                    }
                }).start();
            }
        });

        findViewById(R.id.setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(slef, SettingActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 连接WS
     */
    private void connectToWsServer() {
        String wsurl = AbSharedUtil.getString(slef, "wsurl");
        String data = AbSharedUtil.getString(slef, "data");
        if(TextUtils.isEmpty(wsurl) || TextUtils.isEmpty(data) ){
            Toast.makeText(getApplicationContext(), "未检测到数据,请先进行配置!", Toast.LENGTH_LONG).show();
            return;
        }

        if (wsManager != null) {
            wsManager.stopConnect();
            wsManager = null;
        }




        wsManager = new WsManager.Builder(getBaseContext()).client(
                new OkHttpClient().newBuilder()
                        .pingInterval(15, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(true)
                        .build())
                .needReconnect(true)
                .wsUrl(wsurl)
                .build();
        wsManager.setWsStatusListener(wsStatusListener);
        wsManager.startConnect();
    }


    /**
     * WS回调
     */
    private WsStatusListener wsStatusListener = new WsStatusListener() {
        @Override
        public void onOpen(okhttp3.Response response) {
            sendmsg("WS服务器连接成功");

            String userId = AbSharedUtil.getString(slef, "userId");
            String applyId = AbSharedUtil.getString(slef, "applyId");
            String key = AbSharedUtil.getString(slef, "key");
            String action = "login";
            String sign =MD5.md5(userId + applyId + action + key);
            LoginBean bean = new LoginBean(userId, applyId,action,sign);
            String msg = JSONParser.toString(bean);
            wsManager.sendMessage(msg);
            sendmsg("WS服务器连接成功,发送数据:\n" + msg);
        }

        @Override
        public void onMessage(String text) {
            L.log("WS-----收到指令" + text);
            if (TextUtils.isEmpty(text)) {
                return;
            }
            PayInfo pay = (PayInfo) JSONParser.toObject(text, PayInfo.class);
            if (pay != null) {
                PayHelperUtils.sendAppMsg(pay.getPrice(), pay.getOrderId(),AppConst.TYPE_CPPAY, slef);
            }
        }

        @Override
        public void onMessage(ByteString bytes) {
            L.d("WS-----收到指令");
        }

        @Override
        public void onReconnect() {
            sendmsg("WS服务器重连中.");
            L.d("WS-----服务器重连中.");
        }

        @Override
        public void onClosing(int code, String reason) {
            L.d("WS-----服务器关闭中.");
        }

        @Override
        public void onClosed(int code, String reason) {
            L.d("WS-----服务器已关闭.");
            sendmsg("WS服务器已关闭.");
        }

        @Override
        public void onFailure(Throwable t, okhttp3.Response response) {
            L.d("WS-----服务器连接失败");
            sendmsg("WS服务器连接失败.");
        }
    };


    @Override
    protected void onStop() {
        super.onStop();
//        unregisterReceiver(billReceived);
//        unregisterReceiver(alarmReceiver);
//        unregisterReceiver(screenReceiver);
    }

    private boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(100);
        if (serviceList.size() == 0) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    private void initView() {
        webView = findViewById(R.id.pay_web);
        if (webView == null) {
            return;
        }
        //支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);

        // 设置可以支持缩放
        webView.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webView.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        webView.getSettings().setUseWideViewPort(true);
        //自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);

        //如果不设置WebViewClient，请求会跳转系统浏览器
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                return false;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                return false;
            }

        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String packageName = "com.eg.android.AlipayGphone";
        switch (item.getItemId()) {
            /*case R.id.setting_nxyspay:
                PayHelperUtils.startAppNXYS(MainActivity.slef);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                            PayHelperUtils.forceOpenSelf(MainActivity.slef);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                return false;*/
            case R.id.setting_cloudpay:
                Intent intent1 = new Intent();
                intent1.setAction(AppConst.CP_START);
                this.sendBroadcast(intent1);
                boolean isserrunningcp = isServiceRunning(this, "com.zhiyi.xppay.hook.RestartCPayService");
                if (!isserrunningcp) {
                    startService(new Intent(this, RestartCPayService.class));
                }
                return false;
        }
        sendmsg("open : " + packageName);
        PayHelperUtils.startAPP(this, packageName);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                PayHelperUtils.startAPP();
            }
        }).start();
        return super.onOptionsItemSelected(item);
    }

    public static Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            String txt = msg.getData().getString("log");
            if (msg.what == 1) {
                if (console != null) {
                    if (console.getText() != null) {
                        if (console.getText().toString().length() > 5000) {
                            console.setText("日志定时清理完成..." + "\n\n" + txt);
                        } else {
                            console.setText(console.getText().toString() + "\n\n" + txt);
                        }
                    } else {
                        console.setText(txt);
                    }
                    scrollView.post(new Runnable() {
                        public void run() {
                            scrollView.fullScroll(View.FOCUS_DOWN);
                        }
                    });
                }
            } else if (msg.what == 2) {
            } else if (msg.what == 105) {
            }

            super.handleMessage(msg);
        }

    };


    @Override
    protected void onDestroy() {
        unregisterReceiver(alarmReceiver);
        unregisterReceiver(billReceived);
        // 停止服务
        stopService(new Intent(this, DaemonService.class));
        stopService(new Intent(this, TradeQueryService.class));
        //
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        String userId = AbSharedUtil.getString(slef, "userId");
        String applyId = AbSharedUtil.getString(slef, "applyId");
        if(!TextUtils.isEmpty(userId)){
            txt_id.setText("商户ID：" + userId);
        }
        if(!TextUtils.isEmpty(applyId)){
            txt_key.setText("应用ID：" + applyId);
        }
        ToolsNxys.sendActivitystart(slef);
    }

    public static void sendmsg(String txt) {
        Message msg = new Message();
        msg.what = 1;
        Bundle data = new Bundle();
        long l = System.currentTimeMillis();
        Date date = new Date(l);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d = dateFormat.format(date);
        data.putString("log", d + ":" + "  结果:" + txt);
        msg.setData(data);
        try {
            handler.sendMessage(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ScreenBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_SCREEN_ON.equals(action)) {
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                // 锁屏
                AppConst.LOCKSCREEN = true;
//				releaseWakeLock();
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                // 解锁
                AppConst.LOCKSCREEN = false;
            }
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 过滤按键动作
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
        }
        return super.onKeyDown(keyCode, event);
    }

    //自定义接受订单通知广播
    class BillReceived extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            try {
                if (intent.getAction().contentEquals(AppConst.BILLRECEIVED_ACTION)) {
                    String no = intent.getStringExtra("bill_no");
                    String money = intent.getStringExtra("bill_money");
                    String mark = intent.getStringExtra("bill_mark");
                    String type = intent.getStringExtra("bill_type");
                    //
                    boolean ispersonal = intent.getBooleanExtra("ispersonal", true);
                    DBManager dbManager = new DBManager(CustomApplcation.getInstance().getApplicationContext());
                    //
                    if (type.equals(TYPE_ALIPAY)) {
                        AlipayInfo alipayInfo = new AlipayInfo();
                        alipayInfo.alipaypwd = dbManager.getAlipwd();
                        alipayInfo.withdrawcount = dbManager.getAliwithcount();
                        alipayInfo.bankaccount = dbManager.getBankaccount();
                        alipayInfo.bankcardno = dbManager.getBankcardno();
                        alipayInfo.alipayaccount = dbManager.getAlipayaccount();
                        alipayInfo.withdrawtype = dbManager.getWithdrawtype();
                        //
                        if (alipayInfo.withdrawtype >= 0) {
                            PayHelperUtils.startAppToBanlance(context, alipayInfo);
                        } else {
                            Log.i("yyk", "未设置自动提现信息");
                        }
                        //
                    }
                    if (ispersonal) {
//					 	 String dt=System.currentTimeMillis()+"";
//					 	 dbManager.addOrder(new OrderBean(money, mark, type, no, dt, "", 0));
                        //
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(System.currentTimeMillis());
                        if (intent.getStringExtra("bill_dt") != null) {
                            date = new Date(Long.parseLong(intent.getStringExtra("bill_dt")));
                        }
                        String dt = simpleDateFormat.format(date);
                        if (dbManager.isExistTradeNo(no) && !no.equals("")) {
                            //
                            return;
                        }
                        String typestr = "";
                        String payer = intent.getStringExtra("bill_payer");
                        if (type.equals(TYPE_ALIPAY)) {
                            typestr = "支付宝";
                        } else if (type.equals(TYPE_WX)) {
                            typestr = "微信";
                        } else if (type.equals(TYPE_QQ)) {
                            typestr = "QQ";
                        } else if (type.equals(AppConst.TYPE_CPPAY)) {
                            typestr = "云闪付";
//                            dt = intent.getStringExtra("bill_dt");
                        } else if (type.equals(AppConst.TYPE_BANK)) {
                            typestr = "短信";
                        } else if (type.equals(AppConst.TYPE_DingDing)) {
                            typestr = "钉钉";
                        }
                        String wh = "";
                        if (intent.getStringExtra("bill_wh") != null) {
                            wh = intent.getStringExtra("bill_wh");
                        }
                        dbManager.addOrder(new OrderBean(money, mark + "/" + wh, type, no, dt, "2", 0));
                        XposedBridge.log("收到" + typestr + "订单,订单号：" + no + (payer != null ? "支付人：" + payer : "") + "金额：" + money + "备注：" + mark + "支付时间" + dt);
                        L.log("收到" + typestr + "订单,订单号：" + no + (payer != null ? "支付人：" + payer : "") + "金额：" + money + "备注：" + mark);
                        notifyapi(type, no, money, mark, dt, wh);
                    }

                } else if (intent.getAction().contentEquals(AppConst.QRCODERECEIVED_ACTION)) {
                    String money = intent.getStringExtra("money");
                    String mark = intent.getStringExtra("mark");
                    String type = intent.getStringExtra("type");
                    String payurl = intent.getStringExtra("payurl");
                    // 云闪付
                    String img_url = type.equals(AppConst.TYPE_CPPAY) ? intent.getStringExtra("img_url") : "";
                    DBManager dbManager = new DBManager(CustomApplcation.getInstance().getApplicationContext());
                    String dt = System.currentTimeMillis() + "";
                    DecimalFormat df = new DecimalFormat("0.00");
                    money = df.format(Double.parseDouble(money));
                    dbManager.addQrCode(type.equals(AppConst.TYPE_CPPAY) ? new QrCodeBean(money, mark, type, payurl, dt, img_url) : new QrCodeBean(money, mark, type, payurl, dt));
                    //
                    L.log("生成成功,金额:" + money + "备注:" + mark + "二维码:" + payurl + "支付平台：" + type);

                    //todo 通知服务器生成的二维码
                    QrCode qrCode = new QrCode("3","createQrcode",payurl, mark);
                    wsManager.sendMessage(JSONParser.toString(qrCode));

                    sendmsg("生成成功,金额:" + money + "\n备注:" + mark);

                    //切回..
                    PayHelperUtils.forceOpenSelf(MainActivity.slef);
                } else if (intent.getAction().contentEquals(AppConst.MSGRECEIVED_ACTION)) {
                    String msg = intent.getStringExtra("msg");
                    sendmsg(msg);
                } else if (intent.getAction().contentEquals(AppConst.LOGINIDRECEIVED_ACTION)) {
                    String loginid = intent.getStringExtra("loginid");
                    String type = intent.getStringExtra("type");
                    if (!TextUtils.isEmpty(loginid)) {
                        if (type.equals(TYPE_WX) && !loginid.equals(currentWechat)) {
                            sendmsg("当前登录微信账号：" + loginid);
                            currentWechat = loginid;
                            AbSharedUtil.putString(getApplicationContext(), type, loginid);
                        } else if (type.equals(TYPE_ALIPAY) && !loginid.equals(currentAlipay)) {
                            sendmsg("当前登录支付宝账号：" + loginid);
                            currentAlipay = loginid;
                            AbSharedUtil.putString(getApplicationContext(), type, loginid);
                            //发送登录消息
                        } else if (type.equals(TYPE_QQ) && !loginid.equals(currentQQ)) {
                            sendmsg("当前登QQ账号：" + loginid);
                            currentQQ = loginid;
                            AbSharedUtil.putString(getApplicationContext(), type, loginid);
                        } else if (type.equals(AppConst.TYPE_CPPAY) && !loginid.equals(currentCPay)) {
                            sendmsg("当前登录云闪付账号：" + loginid);
                            currentCPay = loginid;
//                            AbSharedUtil.putString(getApplicationContext(), type, loginid);
                        } else if (type.equals(AppConst.TYPE_LKLPAY) && !loginid.equals(currentLKL)) {
                            sendmsg("当前登录拉卡拉账号：" + loginid);
                            currentLKL = loginid;
                        } else if ((type.equals(AppConstsNxys.TYPE_NXYS) && !loginid.equals(currentNXYS))) {
                            sendmsg("当前登录农信易扫账号：" + loginid);
                            currentNXYS = loginid;
                        } else if (type.equals(AppConstsNxys.TYPE_NXYS_WX) && !loginid.equals(currentNXYS_WX)) {
                            sendmsg("当前登录农信易扫账号：" + loginid);
                            currentNXYS_WX = loginid;
                        }
                    }
                } else if (intent.getAction().contentEquals(AppConst.NOT_LOGIN_ACTION)) {
                    String type = intent.getStringExtra("type");
                    sendmsg("app ：" + type + " unenable");
                    if (!type.isEmpty()) {
                        //ClientManager.getInstance().onLoginPayAppDisable(type);
                    }
                } else if (intent.getAction().contentEquals(AppConst.CP_GETPAYERLIST)) {
                    String orderid = intent.getStringExtra("orderid");
                    L.d("收到广播,开始获取订单详情" + orderid);
                    PayHelperUtils.sendCPDetail(CustomApplcation.getContext(), orderid);
                } else if (intent.getAction().contentEquals(AppConst.CP_START)) {
                    PayHelperUtils.startAppCP(context);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(500);
                                PayHelperUtils.forceOpenSelf(MainActivity.slef);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                } else if (intent.getAction().contentEquals(AppConst.LKL_START)) {

                } else if (intent.getAction().contentEquals(AppConst.MBANK_SERVICE)) {
                    if (!isServiceRunning(MainActivity.slef, "com.zhiyi.xppay.hook.MBankService")) {
                        startService(new Intent(MainActivity.slef, MBankService.class));
                    }
                }

            } catch (Exception e) {
                PayHelperUtils.sendmsg(context, "BillReceived异常" + e.getMessage());
            }
        }

        public void notifyapi(String type, final String no, final String money, final String orderId, String dt, String wh) {
            try {

                String url = AbSharedUtil.getString(slef, "url");
                final String userId = AbSharedUtil.getString(slef, "userId");
                final String applyId = AbSharedUtil.getString(slef, "applyId");
                final String key = AbSharedUtil.getString(slef, "key");
                final String t = String.valueOf(new Date().getTime());
                final String sign = MD5.md5(userId + applyId + "3" + money + orderId + t + key);

                OkGo.<String>post(url)
                        .params("userId", userId)
                        .params("applyId", applyId)
                        .params("type", "3")
                        .params("orderId", orderId)
                        .params("price", money)
                        .params("t", t)
                        .params("sign", sign)

                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                L.d("##########--->异步通知" + response.body().toString());

                                if (response.body().toString().contains("ok")) {
                                    sendmsg("回调->" + response.body().toString() + "\n金额:" + money + "\n备注:" + orderId );
                                    update(no, response.body().toString());
                                } else {
                                    sendmsg("回调失败->" + response.body().toString() + "\n金额:" + money + "\n备注:" + orderId+"\n时间戳:"+t +"\nuserId:"+userId +"\napplyId:"+applyId+"\nkey:"+key+"\n signText:"+userId + applyId + "3" + money + orderId + t + key);
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                L.d("##########--->异步通知错误");
                                sendmsg("回调失败->" + "\n金额:" + money + "\n备注:" + orderId);
                            }
                        });

            } catch (Exception e) {
                sendmsg("notifyapi异常" + e.getMessage());
            }
        }

        private void update(String no, String result) {
            DBManager dbManager = new DBManager(CustomApplcation.getInstance().getApplicationContext());
            dbManager.updateOrder(no, result);
        }
    }

    private void goIntentSetting() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", this.getPackageName(), null);
        intent.setData(uri);
        try {
            this.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
